<?php
/**
 * 项目相关函数
 */

/**
 * 生成并输出验证码
 *
 * @param  string  $phrase
 * @param  integer $width
 * @param  integer $height
 * @throws \Exception
 */
function captcha_output($phrase = null, $width = null, $height = null)
{
    if (! class_exists('\Gregwar\Captcha\CaptchaBuilder')) {
        throw new \Exception('Require components: Gregwar\Captcha (ref: https://github.com/Gregwar/Captcha)');
    }

    service('response')->setContentType('image/jpeg');

    $builder = new \Gregwar\Captcha\CaptchaBuilder($phrase);

    // 输出验证码
    $builder
        ->setMaxAngle(5) // 最大倾斜角度
        ->setMaxOffset(2) // 最大偏移距离
        ->setTextColor(mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120)) // 文本颜色
        ->setBackgroundColor(mt_rand(220, 255), mt_rand(220, 255), mt_rand(180, 255)) // 背景颜色
        ->setMaxFrontLines(0) // 最大前景干扰线数量
        ->setMaxBehindLines(5) // 最大背景干扰线数量
        ->build($width, $height)
        ->output();

    // 存储到 session 中
    service('session')->set('captcha_phrase', strtolower($builder->getPhrase()));
}

/**
 * 校验验证码的正确性
 *
 * @param  string  $phrase
 * @return boolean
 */
function captcha_validate($phrase)
{
    return strtolower($phrase) === service('session')->get('captcha_phrase', false);
}

/**
 * 销毁验证码
 *
 * @param  string  $phrase
 * @return boolean
 */
function captcha_destroy()
{
    service('session')->remove('captcha_phrase');
}

/**
 * 获取 js 目录名
 *
 * @return string
 */
function js_dir()
{
    return PRODUCTION ? 'js' : 'js_src';
}

/**
 * 获取 JS 网址
 *
 * @param  string  $jsfile
 * @param  boolean $jsfile
 * @return string
 */
function js_url($jsfile = null, $time = true)
{
    $jsfile = ltrim($jsfile, '/');

    if (empty($jsfile)) {
        $time = false;
    }

    return static_url(js_dir() . '/' . $jsfile, $time);
}

/**
 * 加载 RequireJS
 *
 * @param  string $name
 * @return string
 */
function require_js($name)
{
    $baseUrl = js_url();
    $urlArgs = PRODUCTION ? app_update_time() : time();
    $bootup  = js_url('require/bootup.js');

    return <<<RJS
<script type="text/javascript" src="{$bootup}"></script>
<script type="text/javascript">
new BootUp([
    '{$baseUrl}require/require.js',
    '{$baseUrl}config.js',
    '{$baseUrl}{$name}.js'
], {
    version: '{$urlArgs}',
    success: function () {
        require({
            baseUrl: '{$baseUrl}',
            urlArgs: '{$urlArgs}'
        });
    }
});
</script>
RJS;
}

/**
 * 发送邮件
 *
 * @param  string|array $to
 * @param  string       $subject
 * @param  string       $body
 * @param  arrray       $params
 * @param  string       $contentType
 * @return integer
 * @throws \Exception
 */
function send_mail($to, $subject, $body, array $params = null, $contentType = 'text/html')
{
    if (! class_exists('\Swift_Mailer')) {
        throw new \Exception('Require components: Swift_Mailer (ref: http://swiftmailer.org/)');
    }

    if (empty($to) || ! is_email($to) || empty($subject) || empty($body)) {
        return false;
    }

    $config = config('mail.smtp');

    // 创建 transport
    $transport = \Swift_SmtpTransport::newInstance($config->host, $config->port)
        ->setUsername($config->username)
        ->setPassword($config->password);

    // 创建邮件消息
    $message = \Swift_Message::newInstance($subject, $body, $contentType);

    // 发件人
    if (isset($params['from'])) {
        $message->setFrom($params['from']);
    } else {
        $message->setFrom($config->from->mail, $config->from->name);
    }

    // 收件人
    if (isset($params['to'])) {
        $message->setTo($params['to']);
    } else {
        $message->setTo($to);
    }

    // 抄送
    if (isset($params['cc'])) {
        $message->setCc($params['cc']);
    }

    // 暗送
    if (isset($params['bcc'])) {
        $message->setBcc($params['bcc']);
    }

    // 回复
    if (isset($params['reply-to'])) {
        $message->setReplyTo($params['reply-to']);
    }

    // 添加附件
    if (isset($params['files'])) {
        $files = is_array($params['files']) ? $params['files'] : array($params['files']);
        foreach ($files as $file) {
            if (is_file($file)) {
                $message->attach(\Swift_Attachment::fromPath($file));
            }
        }
    }

    // 发送邮件
    return \Swift_Mailer::newInstance($transport)->send($message);
}

/**
 * 生成 gravatar 头像地址
 *
 * @see    http://cn.gravatar.com/
 * @param  string  $email
 * @param  integer $width
 * @return string
 */
function gravatar_url($email, $width = 30)
{
    return "http://s.gravatar.com/avatar/" . md5(strtolower($email)) . "?s={$width}";
}

/**
 * 获取 \EasyCSV\Reader
 *
 * @param  string $csvfile
 * @return \EasyCSV\Reader
 * @throws \Exception
 */
function csv_reader($csvfile)
{
    if (! class_exists('\EasyCSV\Reader')) {
        throw new \Exception('Require components: EasyCSV (ref: https://github.com/jwage/easy-csv)');
    }

    return new \EasyCSV\Reader($csvfile);
}

/**
 * 获取 \EasyCSV\Writer
 *
 * @param  string $csvfile
 * @return \EasyCSV\Writer
 * @throws \Exception
 */
function csv_writer($csvfile)
{
    if (! class_exists('\EasyCSV\Writer')) {
        throw new \Exception('Require components: EasyCSV (ref: https://github.com/jwage/easy-csv)');
    }

    return new \EasyCSV\Writer($csvfile);
}

/**
 * 获得 SQL 查询构造器实例
 * 由于 Phalcon 无法生成并输出 SQL，可使用 Aura.SqlQuery 构造 SQL 语句
 *
 * @param  string $db 数据库类型 (Mysql, Pgsql, Sqlite, Sqlsrv)
 * @return \Aura\SqlQuery\QueryFactory
 */
function sql_builder($db = 'mysql')
{
    static $instances = array();

    if (! class_exists('\Aura\SqlQuery\QueryFactory')) {
        throw new \Exception('Require components: Aura.SqlQuery (ref: https://github.com/auraphp/Aura.Sql_Query/tree/rename)');
    }

    $db = strtolower($db);

    if (! isset($instances[$db])) {
        $instances[$db] = new \Aura\SqlQuery\QueryFactory($db);
    }

    return $instances[$db];
}

/**
 * 获得 select 查询语句构造器
 *
 * @param  string $db
 * @return \Aura\SqlQuery\Common\SelectInterface
 */
function sql_builder_select($db = 'mysql')
{
    return sql_builder($db)->newSelect();
}

/**
 * 获得 insert 查询语句构造器
 *
 * @param  string $db
 * @return \Aura\SqlQuery\Common\InsertInterface
 */
function sql_builder_insert($db = 'mysql')
{
    return sql_builder($db)->newInsert();
}

/**
 * 获得 update 查询语句构造器
 *
 * @param  string $db
 * @return \Aura\SqlQuery\Common\UpdateInterface
 */
function sql_builder_update($db = 'mysql')
{
    return sql_builder($db)->newUpdate();
}

/**
 * 获得 delete 语句构造器
 *
 * @param  string $db
 * @return \Aura\SqlQuery\Common\DeleteInterface
 */
function sql_builder_delete($db = 'mysql')
{
    return sql_builder($db)->newDelete();
}
